package tw.twandroidproj.app.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.model.SmsModel;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.NetworkManager;
import tw.twandroidproj.app.network.OnResponseListener;

public class SignupActivity extends ActionBarActivity {
    private EditText editText_username;
    private EditText editText_phone;
    private EditText editText_password;
    private EditText editText_passwordre;
    private Button button_signup;
    private Button button_getcode;
    private  EditText editText_signupcode;
    private NetworkManager networkManager;
    private Context context;
    private time_count time=new time_count(60000,1000);
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_signup, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        setContentView(R.layout.activity_signup);
        context = getBaseContext();
        networkManager=NetworkManager.getInstance(this);


        editText_phone = (EditText) findViewById(R.id.signup_phone);

        editText_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (editText_phone.getText().toString().trim().equals("")) {

                    editText_phone.setError("手机号码不能为空！");
                } else if (editText_phone.getText().toString().trim().length() != 11) {
                    editText_phone.setError("手机号码格式不正确！");
                }
            }
        });
        editText_username = (EditText) findViewById(R.id.signup_username);

        editText_username.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (editText_username.getText().toString().trim().equals("")) {

                    editText_username.setError("用户名不能为空！");
                } else if (editText_username.getText().toString().trim().length() > 16) {
                    editText_username.setError("用户名不能超过16个字符！");
                }
            }
        });

        editText_password = (EditText) findViewById(R.id.signup_password);

        editText_password.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (editText_password.getText().toString().trim().equals("")){

                    editText_password.setError("密码不能为空！");
                }else if (editText_password.getText().toString().trim().length()<6){
                    editText_password.setError("密码不能小于6位！");
                }
            }
        });


        editText_passwordre = (EditText) findViewById(R.id.signup_password_repeat);

        editText_passwordre.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (!editText_passwordre.getText().toString().trim().equals(editText_password.getText().toString().trim())) {

                    editText_passwordre.setError("两次密码输入不一致！");
                }
            }
        });

        editText_signupcode = (EditText) findViewById(R.id.signup_code);
        button_getcode= (Button) findViewById(R.id.getcode);
        button_getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                networkManager.getSmsCode(editText_phone.getText().toString(),
                        new OnResponseListener<SmsModel>() {
                    @Override
                    public void onSuccess(SmsModel result) {
                        Toast.makeText(context, "验证码已发送", Toast.LENGTH_SHORT).show();
                        time.start();//倒计时60s
                    }

                    @Override
                    public void onFailed(ErrorModel errorModel) {
                        Toast.makeText(context, "发送失败了", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

        button_signup= (Button) findViewById(R.id.signup_ok);
        button_signup.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {
                if(checkEdit()) {
                    Log.i("signup", "ok");
                    networkManager.registerByPhone(editText_phone.getText().toString(),
                            editText_password.getText().toString(),
                            editText_username.getText().toString(),
                            editText_signupcode.getText().toString(),
                            new OnResponseListener<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                }

                                @Override
                                public void onFailed(ErrorModel errorModel) {
                                    if (errorModel.getStatus_code() == 430)
                                        Toast.makeText(context, "手机号和验证码不符", Toast.LENGTH_SHORT).show();
                                    else if (errorModel.getStatus_code() == 431)
                                        Toast.makeText(context, "验证码过期", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(context,"error",Toast.LENGTH_SHORT).show();
                                }
                            });

                }
                else{
                    return;
                }
            }
        });



    }
    private boolean checkEdit(){
        if(editText_username.getText().toString().trim().equals("")){
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }else if(editText_username.getText().toString().trim().length() > 16){
            Toast.makeText(this, "用户名不能大于十六个字符", Toast.LENGTH_SHORT).show();
        }else if(editText_phone.getText().toString().trim().equals("")){
            Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
        }else if(editText_phone.getText().toString().trim().length() != 11){
            Toast.makeText(this, "手机号格式不对", Toast.LENGTH_SHORT).show();
        }else if(editText_password.getText().toString().trim().equals("")){
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
        }else if(editText_password.getText().toString().trim().length()<6){
            Toast.makeText(this, "密码不能小于六位", Toast.LENGTH_SHORT).show();
        }else if(!editText_passwordre.getText().toString().trim().equals(editText_passwordre.getText().toString().trim())){
            Toast.makeText(this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
        }else{
            return true;
        }
        return false;
    }

class time_count extends CountDownTimer{

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public time_count(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        button_getcode.setClickable(false);
        button_getcode.setText((millisUntilFinished/1000)+"秒后可重发");
    }

    @Override
    public void onFinish() {
button_getcode.setClickable(true);
        button_getcode.setText("重新获取验证码");
    }
}

}
